import { RouteRecordRaw } from 'vue-router'

export interface MenuProps {
  key: string
  name: string
  title: string
  icon?: string
  path?: string
  children?: MenuProps[]
}

export function filterRouter<T extends RouteRecordRaw, K extends keyof T>(routerList: T | T[], ignore: string[], matchMode?: K): T[] {
  // 校验是否是Array类型，不是转换成Array类型
  const routes: T[] = Object.prototype.toString.call(routerList) === '[object Array]' ? (routerList as T[]) : [routerList as T]
  if (ignore.length === 0) return routes
  if (routes.length === 0) return []
  return routes.filter(({ [matchMode ?? 'name']: matchValue, meta }) => {
    return !ignore.includes(matchValue as string) && !meta?.hideInMenu
  })
}

export function generatorMenu<T extends RouteRecordRaw>(routerMap: T[]): MenuProps[] {
  const ignore = ['notFound', 'root', 'login', '403', '404', '500']
  return filterRouter(routerMap, ignore, 'name').map((item) => {
    const currentMenu = {
      title: item.meta?.title as string,
      name: item.name as string,
      key: item.name as string,
      icon: item.meta?.icon,
      children: [] as MenuProps[]
    }
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      // Recursion
      currentMenu.children = generatorMenu(item.children)
    }
    return currentMenu
  })
}
